<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="80%"
    :before-close="dialogBeforeClose"
    :destroy-on-close="destroyOnClose"
    v-bind="$attrs"
  >
    <div class="app-container">
      <el-row :gutter="20">
        <!--企业/机构数据-->
        <el-col :span="4" :xs="24">
          <div class="head-container">
            <el-input
              v-model="deptName"
              placeholder="请输入企业/机构名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container">
            <el-tree
              :data="deptOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              default-expand-all
              highlight-current
              node-key="id"
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
        <!--用户数据-->
        <el-col :span="20" :xs="24">
          <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
            <el-form-item label="用户名称" prop="userName">
              <el-input
                v-model="queryParams.userName"
                placeholder="请输入用户名称"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model="queryParams.phonenumber"
                placeholder="请输入手机号码"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>

            <el-form-item label="创建时间">
              <el-date-picker
                v-model="dateRange"
                size="small"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table
            v-loading="loading"
            ref="table"
            :data="userList"
            :row-key="field"
            :highlight-current-row="!multiSelect"
            @selection-change="handleSelectionChange"
            @current-change="handleCurrentChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="用户编号" align="center" prop="userId" />
            <el-table-column label="用户名称" align="center" prop="userName" :show-overflow-tooltip="true" />
            <el-table-column label="真实姓名" align="center" prop="nickName" :show-overflow-tooltip="true" />
            <el-table-column label="企业/机构" align="center" prop="dept.deptName" :show-overflow-tooltip="true" />
            <el-table-column label="手机号码" align="center" prop="phonenumber" />
            <el-table-column label="创建时间" align="center" prop="createTime">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>
    </div>
    <div slot="footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listUser } from '@/api/system/user'

import { treeselect } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'UserSelectDialog',
  components: { Treeselect },
  props: {
    multiSelect: { type: Boolean, default: false },
    field: { type: String, default: 'userName' },
    // 弹出层标题
    title: { type: String, default: '选择用户' },
    // 当前选中
    selection: { type: [Array, String, Number] },

    visible: { type: Boolean, default: false },
    destroyOnClose: { type: Boolean, default: false },
  },
  model: {
    prop: 'selection',
    event: 'change',
  },
  data() {
    return {
      // 遮罩层
      loading: true,

      model: null,

      currentRow: null,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,

      // 企业/机构树选项
      deptOptions: undefined,

      // 企业/机构名称
      deptName: undefined,

      // 日期范围
      dateRange: [],

      // 岗位选项
      // 角色选项
      // 表单参数
      defaultProps: {
        children: 'children',
        label: 'label',
      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: '0',
        deptId: undefined,
      },
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      },
    },
  },
  watch: {
    // 根据名称筛选企业/机构树
    deptName(val) {
      this.$refs.tree.filter(val)
    },
    selection(val) {
      if (this.multiSelect) {
        this.setCurrentRow(val)
      } else {
        this.toggleSelection(val)
      }
    },
  },
  created() {
    this.getList()
    this.getTreeselect()
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then((response) => {
        this.userList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询企业/机构下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.getList()
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.queryParams.deptId = null
      this.$refs['tree'].setCurrentKey(null)
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    toggleSelection(selection = []) {
      this.userList.forEach((row) => {
        if (selection.includes(row[this.field])) {
          this.$refs.table.toggleRowSelection(row)
        }
      })
    },

    // 单选
    setCurrentRow(val) {
      const row = this.userList.find((row) => row[this.field] === val)
      this.$refs.table.setCurrentRow(row)
    },
    handleCurrentChange(currentRow, oldRow) {
      console.log(currentRow)
      this.currentRow = currentRow
      if (!this.multiSelect) {
        this.model = currentRow[this.field]
      }
    },

    dialogBeforeClose() {
      this.dialogVisible = false
    },

    submit() {
      this.dialogVisible = false
      this.$emit('change', this.model, this.currentRow)
    },
  },
}
</script>

<style></style>
